package com.tarena.lbs.business.servcie.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.dao.repository.BusinessRepository;
import com.tarena.lbs.business.dao.repository.ChainRepository;
import com.tarena.lbs.business.dao.repository.StoreRepository;
import com.tarena.lbs.business.pojo.param.ChainQuery;
import com.tarena.lbs.business.pojo.param.StoreParam;
import com.tarena.lbs.business.pojo.po.BusinessPO;
import com.tarena.lbs.business.pojo.po.ChainPO;
import com.tarena.lbs.business.pojo.po.StorePO;
import com.tarena.lbs.business.pojo.query.AreaStoreQuery;
import com.tarena.lbs.business.pojo.query.StoreQuery;
import com.tarena.lbs.business.pojo.vo.BusinessStoreVO;
import com.tarena.lbs.business.pojo.vo.ChainVO;
import com.tarena.lbs.business.pojo.vo.PictureVO;
import com.tarena.lbs.business.pojo.vo.StoreVO;
import com.tarena.lbs.business.servcie.BusinessService;
import com.tarena.lbs.business.servcie.StoreService;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class StoreServiceImpl implements StoreService {
    @Autowired
    private StoreRepository storeRepository;
    @Autowired
    private BusinessRepository businessRepository;
    @Autowired
    private ChainRepository chainRepository;
    @Autowired
    private BusinessService businessService;
    @DubboReference
    private UserApi userApi;
    @DubboReference
    private AttachApi attachApi;
    @Override
    public PageResult<StoreVO> pageList(StoreQuery query) {
        log.info("查询店铺列表，入参:{}",query);
        Roles role = AuthenticationContextUtils.get().getRole();
        if (role!=Roles.SHOP){
            throw new RuntimeException("权限不足");
        }
        AdminDto adminById = userApi.getAdminById(AuthenticationContextUtils.get().getId());
        if (adminById==null){
            throw new RuntimeException("商家不存在");
        }
        query.setBusinessId(adminById.getBusinessId());
        log.info("查询商家111111111111111111入参:{}",query);
        PageResult<StoreVO> voPage = new PageResult<>();
        PageInfo<StorePO> pageInfo = storeRepository.pageList(query);
        voPage.setPageNo(pageInfo.getPageNum());
        voPage.setTotal(pageInfo.getTotal());
        voPage.setPageSize(pageInfo.getPageSize());
        List<StoreVO> vos = null;
        List<StorePO> pos = pageInfo.getList();
        if (CollectionUtils.isNotEmpty(pos)){
            vos=pos.stream().map(po->{
                StoreVO vo = new StoreVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        voPage.setObjects(vos);
        return voPage;
    }

    @Override
    public void save(StoreParam param) {
        log.info("保存店铺信息，入参:{}",param);
        Roles role = AuthenticationContextUtils.get().getRole();
        if (role!=Roles.SHOP){
            throw new RuntimeException("权限不足");
        }
        BusinessPO bpo = businessRepository.findById(param.getBusinessId());
        if (bpo==null){
            throw new RuntimeException("商家不存在");
        }
        if (param.getId()!=null){
            StorePO po = new StorePO();
            BeanUtils.copyProperties(param,po);
            po.setStoreLongitude(param.getLongitude());
            po.setStoreLatitude(param.getLatitude());
            po.setUpdateTime(new Date());
            storeRepository.updateStatus(po);
            return;
        }
        StorePO po = new StorePO();
        BeanUtils.copyProperties(param,po);
        po.setStoreImagesId(param.getStoreImagesIds().stream().map(id->id+"").collect(Collectors.joining(",")));
        po.setCreateTime(new Date());
        po.setStoreLatitude(param.getLatitude());
        po.setStoreLongitude(param.getLongitude());
        storeRepository.save(po);
        ChainPO chainPO = new ChainPO();
        chainPO.setStoreId(po.getId());
        chainPO.setLinkStatus(0);
        chainPO.setCreateTime(new Date());
        //生成一段随机的链接
        chainPO.setLink("https:www.fadawdasf.com"+po.getId());
        chainPO.setLinkImage("TODO");
        chainRepository.save(chainPO);
    }

//    @Override
//    public PageResult<ChainVO> getAllChain(ChainQuery query) {
//        query.setBusinessId(0);
//        log.info("查询所有连锁店，入参:{}",query);
//        PageResult<ChainVO> voPage = new PageResult<>();
//        PageInfo<ChainPO> pageInfo = chainRepository.pageList(query);
//        log.info("查询所有连锁店，出参:{}",pageInfo.getList());
//        // 将分页信息中的页码设置到分页结果对象中
//        voPage.setPageNo(pageInfo.getPageNum());
//        // 将分页信息中的每页数量设置到分页结果对象中
//        voPage.setPageSize(pageInfo.getPageSize());
//        // 将分页信息中的总记录数设置到分页结果对象中
//        voPage.setTotal(pageInfo.getTotal());
//        List<ChainVO> vos = null;
//        List<ChainPO> pos = pageInfo.getList();
//        if (CollectionUtils.isNotEmpty(pos)) {
//            vos = pos.stream().map(po -> {
//                ChainVO vo = new ChainVO();
//                BeanUtils.copyProperties(po, vo);
//                //将门店信息封裝到查出的結果中
//                StoreVO svo = new StoreVO();
//                BeanUtils.copyProperties(spo, svo);
//                vo.setStore(svo);
//                vo.setStoreAddress(spo.getStoreLocation());
//                vo.setStoreName(spo.getStoreName());
//                //將商家信息封裝到查出 的結果中
//                BusinessStoreVO business = businessService.busiStoreDetail(spo.getBusinessId());
//                vo.setBusinessName(business.getBusinessName());
//                vo.setBusiness(business);
//                return vo;
//            }).collect(Collectors.toList());
//        }
//        voPage.setObjects(vos);
//        return voPage;
//    }
    public PageResult<ChainVO> getAllChain(ChainQuery query) {
        AdminDto adminById = userApi.getAdminById(AuthenticationContextUtils.get().getId());
        if (adminById==null){
            throw new RuntimeException("商家不存在");
        }
        query.setBusinessId(adminById.getBusinessId());
        log.info("查询所有二维码，入参:{}",query);
        PageResult<ChainVO> voPage = new PageResult<>();
        List<StorePO> pos = storeRepository.storeEdit(query);
        log.info("查询所有二维码，出参:{}",pos);
        if (pos == null || pos.size() == 0){
            // 不返回null，而是返回一个空的PageResult
            voPage.setObjects(new ArrayList<>());
            voPage.setPageNo(1);
            voPage.setPageSize(10);
            voPage.setTotal(0L);
            return voPage;
        }
        query.setStoreId(pos.stream().map(po->po.getId()).collect(Collectors.toList()));
        PageInfo<ChainPO> pageInfo = chainRepository.pageList(query);
        log.info("查询所有二维码，出参:{}",pageInfo.getList());
        // 将分页信息中的页码设置到分页结果对象中
        voPage.setPageNo(pageInfo.getPageNum());
        // 将分页信息中的每页数量设置到分页结果对象中
        voPage.setPageSize(pageInfo.getPageSize());
        // 将分页信息中的总记录数设置到分页结果对象中
        voPage.setTotal(pageInfo.getTotal());
        BusinessStoreVO business = businessService.busiStoreDetail(query.getBusinessId());
        List<ChainVO> vos = new ArrayList<>();
        List<ChainPO> pos2 = pageInfo.getList();
// 假设pos和pos2有关联关系，比如通过ID匹配
        if (CollectionUtils.isNotEmpty(pos) && CollectionUtils.isNotEmpty(pos2)) {
            vos = pos.stream().map(storePo -> {
                ChainVO vo = new ChainVO();
                vo.setStoreId(storePo.getId());
                vo.setStoreName(storePo.getStoreName());
                vo.setStoreAddress(storePo.getStoreLocation());
                vo.setBusinessName(business.getBusinessName());

                // 从pos2中查找对应的连锁店信息
                pos2.stream()
                        .filter(chainPo -> chainPo.getStoreId().equals(storePo.getId()))
                        .findFirst()
                        .ifPresent(chainPo -> {
                            vo.setId(chainPo.getId());
                            vo.setLink(chainPo.getLink());
                            vo.setLinkImage(chainPo.getLinkImage());
                            vo.setLinkStatus(chainPo.getLinkStatus());
                        });

                return vo;
            }).collect(Collectors.toList());
        } else if (CollectionUtils.isNotEmpty(pos)) {
            // 只有店铺信息
            vos = pos.stream().map(po -> {
                ChainVO vo = new ChainVO();
                vo.setStoreId(po.getId());
                vo.setStoreName(po.getStoreName());
                vo.setStoreAddress(po.getStoreLocation());
                vo.setBusinessName(business.getBusinessName());
                return vo;
            }).collect(Collectors.toList());
        } else if (CollectionUtils.isNotEmpty(pos2)) {
            // 只有连锁店信息
            vos = pos2.stream().map(po -> {
                ChainVO vo = new ChainVO();
                vo.setId(po.getId());
                vo.setLink(po.getLink());
                vo.setLinkImage(po.getLinkImage());
                vo.setLinkStatus(po.getLinkStatus());
                return vo;
            }).collect(Collectors.toList());
        }

        voPage.setObjects(vos);
        return voPage;
    }

    @Override
    public void enable(Integer id) {
        log.info("启用店铺，入参:{}",id);
        ChainPO po = chainRepository.findById(id);
        if (po==null){
            throw new RuntimeException("二维码不存在");
        }
        if (po.getLinkStatus()==1){
            po.setLinkStatus(0);
            chainRepository.update(po);
        }
        po.setLinkStatus(1);
        chainRepository.update(po);
        log.info("启用店铺，出参:{}",id);
    }

    @Override
    public void updateStatus(Integer id) {
        log.info("更新店铺状态，入参:{}",id);
        StorePO po = new StorePO();
        po.setId(id);
        po.setStoreStatus(0);
        storeRepository.updateStatus(po);
        log.info("更新店铺状态，出参:{}",id);
    }

    @Override
    public void updateStatusDisable(Integer id) {
        log.info("更新店铺状态为禁用，入参:{}",id);
        StorePO po = new StorePO();
        po.setId(id);
        po.setStoreStatus(1);
        storeRepository.updateStatus(po);
        log.info("更新店铺状态为禁用，出参:{}",id);
    }

    @Override
    public StoreVO getStoreById(Integer id) {
        log.info("查询店铺详情，入参:{}",id);
        
        // 添加参数校验
        if (id == null || id <= 0) {
            log.warn("查询店铺详情时ID参数无效: {}", id);
            return null;
        }
        
        StorePO po = storeRepository.findById(id);
        // 添加空值检查
        if (po == null) {
            log.warn("未找到ID为{}的店铺", id);
            return null;
        }
        
        StoreVO vo = new StoreVO();
        BeanUtils.copyProperties(po,vo);
        
        // 处理店铺图片
        List<PictureVO> pictureVOS = new ArrayList<>();
        if (po.getStoreImagesId() != null && !po.getStoreImagesId().isEmpty()) {
            try {
                String[] imageIds = po.getStoreImagesId().split(",");
                for (String ids : imageIds) {
                    if (ids != null && !ids.trim().isEmpty()) {
                        try {
                            PictureVO pictureVO = new PictureVO();
                            pictureVO.setId(Integer.parseInt(ids.trim()));
                            pictureVO.setImage(attachApi.getAttachUrl(ids.trim()));
                            pictureVOS.add(pictureVO);
                        } catch (NumberFormatException e) {
                            log.warn("图片ID格式错误: {}", ids, e);
                        } catch (Exception e) {
                            log.warn("获取图片URL失败，图片ID: {}", ids, e);
                        }
                    }
                }
            } catch (Exception e) {
                log.error("处理店铺图片时发生异常", e);
            }
        }
        vo.setPictureVOS(pictureVOS);
        
        // 处理店铺Logo
        try {
            if (po.getStoreLogo() != null && !po.getStoreLogo().isEmpty()) {
                vo.setStoreLogo(attachApi.getAttachUrl(po.getStoreLogo()));
            }
        } catch (Exception e) {
            log.warn("获取店铺Logo失败，Logo ID: {}", po.getStoreLogo(), e);
        }
        
        log.info("查询店铺详情，出参:{}",vo);
        return vo;
    }

    @Override
    public void deleteStore(Integer id) {
        log.info("删除店铺，入参:{}",id);
        storeRepository.deleteById(id);
        chainRepository.deleteById(id);
        log.info("删除店铺，出参:{}",id);
    }

    @Override
    public PageResult<StoreVO> getStoreByCity(AreaStoreQuery query) {
        AdminDto adminById = userApi.getAdminById(AuthenticationContextUtils.get().getId());
        if (adminById==null){
            throw new RuntimeException("商家不存在");
        }
        Integer businessId = (adminById.getBusinessId());
        query.setBusinessId(businessId);
        log.info("查询城市下的店铺，入参:{}",query);
        PageResult<StoreVO> voPage = new PageResult<>();
        PageInfo<StorePO> pageInfo = storeRepository.getStoreByCity(query);
        voPage.setPageNo(pageInfo.getPageNum());
        voPage.setPageSize(pageInfo.getPageSize());
        voPage.setTotal(pageInfo.getTotal());
        List<StoreVO> vos = null;
        List<StorePO> pos = pageInfo.getList();
        if (CollectionUtils.isNotEmpty(pos)){
            vos = pos.stream().map(po -> {
                StoreVO vo = new StoreVO();
                BeanUtils.copyProperties(po,vo);
                return vo;
            }).collect(Collectors.toList());
        }
        voPage.setObjects(vos);
        log.info("查询城市下的店铺，出参:{}",pageInfo.getList());
        return voPage;
    }

}
